<template>
    <div class="popup-container">
        <div class="popup-header">
            <h2>基本配置</h2>

            <!-- <div class="page-status">
                <span :class="['status-indicator', getPageStatusColor()]">
                    {{ getPageStatusText() }}
                </span>
            </div> -->

            <!-- <div class="tab-buttons">
                <button :class="['tab-btn', { active: activeTab === 'form' }]" @click="activeTab = 'form'">
                    配置
                </button>
                <button :class="['tab-btn', { active: activeTab === 'status' }]" @click="activeTab = 'status'">
                    详情
                </button>
            </div> -->

        </div>

        <div class="popup-content">
            <!-- 按钮 -->
            <div class="form-actions">
                <button class="btn btn-primary" @click="handleSubmit">提交</button>
                <button class="btn btn-secondary" @click="handleReset">重置</button>
                <button class="btn btn-success" @click="fillInputField">自动加人</button>
            </div>
            <!-- 表单页面 -->
            <div v-if="activeTab === 'form'" class="form-tab">

                <div class="form-section">
                    <h3>基础配置</h3>
                    <div class="form-row">
                        <label>账号：</label>
                        <input v-model="formData.uname" placeholder="请输入账号" />
                    </div>
                    <div class="form-row">
                        <label>facebook账号：</label>
                        <input v-model="formData.facebookName" placeholder="请输入facebook账号" />
                    </div>
                    <div class="form-row">
                        <label>facebook密码：</label>
                        <input v-model="formData.facebookPassword" placeholder="请输入facebook密码" />
                    </div>
                </div>

            </div>

            <!-- 状态页面 -->
            <div v-if="activeTab === 'status'" class="status-tab">
                <div class="status-item">
                    <span class="label">插件状态：</span>
                    <span class="value success">运行中</span>
                </div>
                <div class="status-item">
                    <span class="label">监听状态：</span>
                    <span class="value success">已启动</span>
                </div>
                <div class="status-item">
                    <span class="label">内容收集：</span>
                    <span class="value">{{ collectedCount }} 条</span>
                </div>
                <div class="status-item">
                    <span class="label">点赞次数：</span>
                    <span class="value">{{ likeCount }} 条</span>
                </div>
                <div class="status-item">
                    <span class="label">评论次数：</span>
                    <span class="value">{{ commentCount }} 条</span>
                </div>

                <!-- <div class="status-item">
                    <span class="label">文件生成：</span>
                    <span class="value">{{ hasGeneratedFile ? '已完成' : '等待中' }}</span>
                </div>

                <div class="status-actions">
                    <button class="btn btn-small" @click="resetExtension">重置扩展</button>
                    <button class="btn btn-small" @click="viewContent">查看内容</button>
                </div> -->
            </div>
        </div>

        <!-- 消息提示 -->
        <div v-if="message" :class="['message', messageType]">
            {{ message }}
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

const activeTab = ref('form')
const message = ref('')
const messageType = ref('info')
const collectedCount = ref(0)
const hasGeneratedFile = ref(false)
const likeCount = ref(0)
const commentCount = ref(0)
// const pageSupported = ref(false) // 添加页面支持状态
// const currentPageUrl = ref('') // 添加当前页面URL

const formData = reactive({
    uname: '',
    facebookName: '',
    facebookPassword: ''
})

// 显示消息
const showMessage = (text, type = 'info') => {
    message.value = text
    messageType.value = type
    setTimeout(() => {
        message.value = ''
    }, 3000)
}

// 提交表单
const handleSubmit = () => {

    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        console.log(formData, 'formData1');
        chrome.scripting.executeScript({
            target: { tabId: tabs[0].id },
            func: submitSet,
            args: [formData]
        });
    });

    // console.log(formData, 'formData2');


    // showMessage('表单提交成功！', 'success')
    // console.log('表单数据:', formData)
}

// 重置表单
const handleReset = () => {
    Object.assign(formData, {
        uname: '',
        facebookName: '',
        facebookPassword: '',
    })
    showMessage('表单已重置', 'info')
}

// 重置扩展
const resetExtension = () => {
    // 向 content script 发送消息
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (!tabs || tabs.length === 0) {
            showMessage('无法获取当前标签页', 'error')
            return
        }

        chrome.tabs.sendMessage(tabs[0].id, { action: 'resetExtension' }, (response) => {
            if (chrome.runtime.lastError) {
                console.log('通信错误:', chrome.runtime.lastError.message)
                showMessage('页面未加载完成，请刷新页面后重试1', 'error')
                return
            }

            if (response && response.success) {
                showMessage('扩展已重置', 'success')
                updateStatus()
            } else {
                showMessage('重置失败，请刷新页面', 'error')
            }
        })
    })
}

// 查看内容
const viewContent = () => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (!tabs || tabs.length === 0) {
            showMessage('无法获取当前标签页', 'error')
            return
        }

        chrome.tabs.sendMessage(tabs[0].id, { action: 'viewStoredContent' }, (response) => {
            if (chrome.runtime.lastError) {
                console.log('通信错误:', chrome.runtime.lastError.message)
                showMessage('页面未加载完成，请刷新页面后重试2', 'error')
                return
            }

            if (response && response.content) {
                showMessage(`当前收集了 ${response.content.length} 条内容`, 'info')
                collectedCount.value = response.content.length
            } else {
                showMessage('暂无收集的内容', 'info')
            }
        })
    })
}



// 填充输入框
const fillInputField = () => {

    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        if (tabs.length > 0) {

            console.log(tabs, 'tabs');
            const baseUrl = 'https://mv.bckj.site/basic-api'; // 替换为你的实际API地址
            const apiUrl = `${baseUrl}/sys/task/user/add/history/get/add/friend/task`;

            console.log("请求API地址:", apiUrl);
            const interval = setInterval(async () => {
                const response = await fetch(apiUrl, {
                    method: "GET",
                    headers: {
                        "Content-Type": "application/json"
                    },
                });

                if (!response.ok) {
                    console.error("API请求失败:", response.status, response.statusText);
                    return;
                }

                const data = await response.json();
                if (data.code !== 200) {
                    console.log("无数据，无法加人:", data);
                    return;
                }

                console.log("获取任务成功:", data);
                console.log(data.data.infoUrl, 'data.data.infoUrl');
                if (!data.data.infoUrl) {
                    console.log("无数据，无法加人");
                    return;
                }

                chrome.tabs.update(tabs[0].id, { url: data.data.infoUrl }, function () {
                    if (chrome.runtime.lastError) {
                        console.error("更新标签页失败:", chrome.runtime.lastError);
                    } else {
                        console.log("已跳转到:", data.data.url);
                        setTimeout(() => {

                            chrome.scripting.executeScript({
                                target: { tabId: tabs[0].id },
                                func: typeAndEnter,
                                args: [data.data.id, data.data.infoId, interval]
                            });

                        }, 8000);
                    }
                });
            }, 20000)

        } else {
            console.error("没有找到活动标签页");
        }
    });
}

// 更新状态
const updateStatus = () => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (!tabs || tabs.length === 0) {
            console.log('无法获取当前标签页')
            return
        }

        chrome.tabs.sendMessage(tabs[0].id, { action: 'getExtensionStatus' }, (response) => {
            if (chrome.runtime.lastError) {
                console.log('通信错误:', chrome.runtime.lastError.message)
                // 设置默认状态
                hasGeneratedFile.value = false
                collectedCount.value = 0
                return
            }

            if (response) {
                hasGeneratedFile.value = response.hasGeneratedFile
                // 获取收集的内容数量
                chrome.tabs.sendMessage(tabs[0].id, { action: 'viewStoredContent' }, (contentResponse) => {
                    if (chrome.runtime.lastError) {
                        console.log('获取内容通信错误:', chrome.runtime.lastError.message)
                        collectedCount.value = 0
                        return
                    }

                    if (contentResponse && contentResponse.content) {
                        collectedCount.value = contentResponse.content.length
                    } else {
                        collectedCount.value = 0
                    }
                })
            } else {
                hasGeneratedFile.value = false
                collectedCount.value = 0
            }
        })
    })
}


// 监听来自 content script 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.type === 'statusUpdate') {
        updateStatus()
    }
})

onMounted(() => {

    // checkPageSupport()
    updateStatus()
})

// 检查页面是否支持插件功能
// const checkPageSupport = () => {
//     chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
//         if (!tabs || tabs.length === 0) {
//             pageSupported.value = false
//             currentPageUrl.value = ''
//             return
//         }

//         const tab = tabs[0]
//         currentPageUrl.value = tab.url || ''

//         // 检查是否是支持的页面（HTTPS页面）
//         if (tab.url && tab.url.startsWith('https://')) {
//             pageSupported.value = true
//             // 尝试与内容脚本通信
//             chrome.tabs.sendMessage(tab.id, { action: 'ping' }, (response) => {
//                 if (chrome.runtime.lastError) {
//                     console.log('页面检查通信错误:', chrome.runtime.lastError.message)
//                     pageSupported.value = false
//                 } else if (response && response.success) {
//                     pageSupported.value = true
//                 } else {
//                     pageSupported.value = false
//                 }
//             })
//         } else {
//             pageSupported.value = false
//         }
//     })
// }

// 显示页面状态信息
// const getPageStatusText = () => {
//     if (!pageSupported.value) {
//         return '当前页面不支持插件功能'
//     }
//     return '插件功能已启用'
// }

// // 显示页面状态颜色
// const getPageStatusColor = () => {
//     return pageSupported.value ? 'success' : 'error'
// }

</script>

<style scoped>
.popup-container {
    width: 400px;
    min-height: 500px;
    background: white;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.popup-header {
    /* background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white; */
    padding: 16px;
    text-align: center;
}

.popup-header h2 {
    /* margin: 0 0 12px 0; */
    font-size: 18px;
    font-weight: 600;
}

.page-status {
    margin-bottom: 12px;
    text-align: center;
}

.status-indicator {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
    color: white;
}

.status-indicator.success {
    background: #28a745;
}

.status-indicator.error {
    background: #dc3545;
}

.status-indicator.info {
    background: #17a2b8;
}

.tab-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
}

.tab-btn {
    background: rgba(255, 255, 255, 0.2);
    border: none;
    color: white;
    padding: 6px 16px;
    border-radius: 16px;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.3s ease;
}

.tab-btn.active {
    background: rgba(255, 255, 255, 0.3);
    transform: scale(1.05);
}

.popup-content {
    padding: 16px;
}

.form-section {
    margin-bottom: 20px;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #e9ecef;
}

.form-section h3 {
    margin: 0 0 12px 0;
    font-size: 14px;
    color: #495057;
    font-weight: 600;
}

.form-row {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
}

.form-row label {
    width: 60px;
    font-size: 12px;
    color: #6c757d;
    flex-shrink: 0;
}

.form-row input,
.form-row select {
    flex: 1;
    padding: 6px 8px;
    border: 1px solid #ced4da;
    border-radius: 4px;
    font-size: 12px;
}

.checkbox-group {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
}

.checkbox-group label {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    color: #6c757d;
    cursor: pointer;
}

.checkbox-group input[type="checkbox"] {
    margin: 0;
}

.form-actions {
    display: flex;
    gap: 12px;
    justify-content: center;
    margin-bottom: 20px;
}

.btn {
    padding: 8px 20px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 12px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.btn-primary {
    background: #667eea;
    color: white;
}

.btn-primary:hover {
    background: #5a6fd8;
    transform: translateY(-1px);
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background: #5a6268;
}

.btn-success {
    background: #28a745;
    color: white;
}

.btn-success:hover {
    background: #218838;
    transform: translateY(-1px);
}

.btn-small {
    padding: 6px 12px;
    font-size: 11px;
}

.status-tab {
    padding: 16px 0;
}

.status-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #e9ecef;
}

.status-item:last-child {
    border-bottom: none;
}

.status-item .label {
    font-size: 12px;
    color: #6c757d;
}

.status-item .value {
    font-size: 12px;
    font-weight: 500;
}

.status-item .value.success {
    color: #28a745;
}

.status-actions {
    margin-top: 20px;
    display: flex;
    gap: 8px;
    justify-content: center;
}

.message {
    position: fixed;
    bottom: 16px;
    left: 50%;
    transform: translateX(-50%);
    padding: 8px 16px;
    border-radius: 6px;
    font-size: 12px;
    color: white;
    z-index: 1000;
}

.message.info {
    background: #17a2b8;
}

.message.success {
    background: #28a745;
}

.message.error {
    background: #dc3545;
}
</style>
